//
//  HYConfirmBookingVC.m
//  Booking
//
//  Created by Duntech on 2018/4/24.
//  Copyright © 2018年 Duntech. All rights reserved.
//

#import "HYConfirmBookingVC.h"
#import "HYBookingSuccesssVC.h"
#import "HYTextFieldTableViewCell.h"
#import "HYImageTableViewCell.h"
#import "HYImageTitleTableViewCell.h"
#import "HYSwitchTableViewCell.h"
#import "HYMeetingRemarkCell.h"
#import "HYTextFieldCellModel.h"
#import "HYSelectInvitersVC.h"
#import <ContactsUI/ContactsUI.h>
#import "HYBookSuccessView.h"

@interface HYConfirmBookingVC () <PGDatePickerDelegate,CNContactPickerDelegate,HYTextFieldCellDelegate>

@property (nonatomic,strong) UIButton *confirmBtn;
/** dataSource */
@property (nonatomic,strong) HYTableViewDataSource *dataSource;
/** delegate */
@property (nonatomic,strong) HYTableViewDelegate *delegate;
/** dataSets数据源 */
@property (nonatomic,strong) NSMutableArray *dataSetsArray;
@property (nonatomic,strong) NSMutableArray *sectionArray;
@property (nonatomic,copy)   NSArray *textFieldArray;
@property (nonatomic,strong) NSMutableArray *dataValueArray;
@property (nonatomic,strong) NSMutableArray *timeValueArray;
@property (nonatomic,copy)   NSString *remarkStr;
@property (nonatomic,strong) NSString *organizierIDStr;
@property (nonatomic,strong) NSString *userIDStr;
/** 外来与会者数组 */
@property (nonatomic,strong) NSMutableArray *extennalAttendeesArray;
/** 外来与会者名字 */
@property (nonatomic,strong) NSMutableArray *extennalNameArray;
@property (nonatomic,strong) NSString *extennalAttendeesStr;
@property (nonatomic,assign) NSInteger lastSelectTimeIndex;
@property (nonatomic,strong) UITableView *tableView;

@end

@implementation HYConfirmBookingVC

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self setupSubviews];
    [self setupData];
    [self registerTableViewCell];
    [self bindingTableViewCell];
}

- (void)setupSubviews{
    
    self.title = @"确认预定";
    self.view.backgroundColor = KAPP_WHITE_COLOR;
    self.dataSource.dataSource = self.dataSetsArray;
    self.delegate.dataSource = self.dataSetsArray;
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.confirmBtn];
    
    [_confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(self.view).offset(-20 * WIDTH_MULTIPLE);
        make.left.equalTo(self.view).offset(20 * WIDTH_MULTIPLE);
        make.height.mas_equalTo(50 * WIDTH_MULTIPLE);
    }];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.bottom.equalTo(self.confirmBtn.mas_top);
    }];
}

- (void)setupData{
    
    NSMutableArray *sectionArray = [NSMutableArray array];
    NSMutableArray *timeSectionArray = [NSMutableArray array];
   
    for (NSInteger i = 0; i < self.textFieldArray.count; i++) {
        
        HYTextFieldCellModel *textFieldCellModel = [HYTextFieldCellModel new];
        textFieldCellModel.cellIdientifier = @"HYTextFieldTableViewCell";
        textFieldCellModel.cellHeight = 50;
        textFieldCellModel.title = self.textFieldArray[i];
        textFieldCellModel.placeholderStr = self.textFieldArray[i];
        textFieldCellModel.value = self.dataValueArray[i];
        textFieldCellModel.indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        if (i == 0) {
            textFieldCellModel.inputMode = HYTextFieldCellInputModeInput;
        }
        else{
            textFieldCellModel.inputMode = HYTextFieldCellInputModeSelect;
        }
        [sectionArray addObject:textFieldCellModel];
    }
    
    NSArray *timeArray = @[@"StartTime",@"EndTime"];
    for (NSInteger i = 0; i < timeArray.count; i++) {
        
        HYTextFieldCellModel *textFieldCellModel = [HYTextFieldCellModel new];
        textFieldCellModel.cellIdientifier = @"HYTextFieldTableViewCell";
        textFieldCellModel.cellHeight = 50;
        textFieldCellModel.title = timeArray[i];
        textFieldCellModel.indexPath = [NSIndexPath indexPathForRow:i inSection:1];
        textFieldCellModel.inputMode = HYTextFieldCellInputModeSelect;
        [timeSectionArray addObject:textFieldCellModel];
    }
    
    [self.dataSetsArray addObject:sectionArray];
    [self.dataSetsArray addObject:timeSectionArray];
    [self.tableView reloadData];
}

- (void)registerTableViewCell{
    [self.tableView registerClass:[HYTextFieldTableViewCell class] forCellReuseIdentifier:@"HYTextFieldTableViewCell"];
    [self.tableView registerClass:[HYSwitchTableViewCell class] forCellReuseIdentifier:@"HYSwitchTableViewCell"];
    [self.tableView registerClass:[HYMeetingRemarkCell class] forCellReuseIdentifier:@"HYMeetingRemarkCell"];
}

- (void)bindingTableViewCell{
    
    __weak typeof(self) weakSelf = self;
    [self.delegate setDidSelectedBlock:^(UITableView *tableView, NSIndexPath *indexPath) {
        
        if (indexPath.section == 0) {
            
            if (indexPath.row != 0) {
                
                if (indexPath.row == 3) {
                    
                    if (@available(iOS 9.0, *)) {
                        CNContactPickerViewController *contactPickerViewController = [[CNContactPickerViewController alloc] init];
                        contactPickerViewController.delegate = weakSelf;
                        [weakSelf presentViewController:contactPickerViewController animated:YES completion:nil];
                    }
                    return;
                }
                
                HYSelectInvitersVC *selectVC = [HYSelectInvitersVC new];
                if (indexPath.row == 1) {
                    selectVC.selectType = HYSelectTypeSingle;
                }
                else{
                    selectVC.selectType = HYSelectTypeMultiple;
                }
                [weakSelf.navigationController pushViewController:selectVC animated:YES];
                selectVC.selectBlock = ^(NSMutableArray *userIDArray, NSMutableArray *usernameArray) {
                  
                    NSMutableString *nameStr = [NSMutableString string];
                    for (NSInteger i = 0; i < usernameArray.count; i++) {
                        
                        [nameStr appendString:usernameArray[i]];
                        if (i != usernameArray.count - 1) {
                            
                            [nameStr appendString:@","];
                        }
                    }
                    
                    NSMutableString *tempStr = [NSMutableString string];
                    for (NSInteger i = 0; i < userIDArray.count; i++) {
                        
                        [tempStr appendString:userIDArray[i]];
                        if (i != userIDArray.count - 1) {
                            [tempStr appendString:@","];
                        }
                    }
                    if (indexPath.row == 1) {
                        weakSelf.organizierIDStr = tempStr;
                    }
                    else{
                        weakSelf.userIDStr = tempStr;
                    }
                    
                    [weakSelf.dataValueArray replaceObjectAtIndex:indexPath.row withObject:nameStr];
                    [weakSelf.tableView reloadData];
                };
            }
        }
        else if (indexPath.section == 1){
            
            //选择时间
            weakSelf.lastSelectTimeIndex = indexPath.row;
            PGDatePickManager *datePickManager = [[PGDatePickManager alloc] init];
            datePickManager.isShadeBackgroud = YES;
            PGDatePicker *datePicker = datePickManager.datePicker;
            datePicker.delegate = weakSelf;
            datePicker.datePickerMode = PGDatePickerModeDateHourMinute;
            
            NSDate *currentDate = [NSDate date];
            NSCalendar *calendar = [NSCalendar currentCalendar];//当前用户的calendar
            NSDateComponents * components = [calendar components:NSCalendarUnitYear | NSCalendarUnitSecond | NSCalendarUnitMinute | NSCalendarUnitMonth | NSCalendarUnitHour | NSCalendarUnitDay fromDate:currentDate];
            if (components.minute > 30) {
                components.hour += 1;
            }
            else if(components.minute < 30){
                components.minute = 30;
            }
            datePicker.minimumDate = [calendar dateFromComponents:components];
            datePicker.maximumDate = [NSDate dateWithTimeInterval:30 * 24 * 60 * 60 sinceDate:datePicker.minimumDate];
            datePickManager.isShadeBackgroud = YES;
            [weakSelf presentViewController:datePickManager animated:YES completion:nil];
        }
    }];
    
    [self.delegate setHeaderHeightBlock:^CGFloat(UITableView *tableView, NSInteger section) {
        if (section == 0) {
            return 0;
        }
        else{
            return 44;
        }
    }];
    
    [self.delegate setHeaderViewBlock:^UIView *(UITableView *tableView, NSInteger section) {
        UILabel *headView = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
        headView.backgroundColor = RGBColor(242, 242, 248);
        headView.font = KFont(15);
        headView.textColor = RGBColor(136, 136, 136);
        if (section == 1) {
            headView.text = @"    会议时间";
        }
        else if (section == 2){
            headView.text = @"    会议详情（200字以内）";
        }
        
        return headView;
    }];
    
    [self.dataSource setBindingCellBlock:^(UITableView *tableView, id rowDataSource, HYBaseTableViewCell *cell, NSIndexPath *indexPath) {
       
        
        if (indexPath.section == 0) {
            
            HYTextFieldTableViewCell *textFieldCell = (HYTextFieldTableViewCell *)cell;
            textFieldCell.indexPath = indexPath;
            textFieldCell.delegate = weakSelf;
            textFieldCell.valueStr = weakSelf.dataValueArray[indexPath.row];
        }
        else if (indexPath.section == 1){
            HYTextFieldTableViewCell *textFieldCell = (HYTextFieldTableViewCell *)cell;
            textFieldCell.valueStr = weakSelf.timeValueArray[indexPath.row];
        }
        else if (indexPath.section == 2){
            
            HYMeetingRemarkCell *remarkCell = (HYMeetingRemarkCell *)cell;
            remarkCell.remarkStr = weakSelf.remarkStr;
            remarkCell.inputTextChangeBlock = ^(NSString *inputText) {
                weakSelf.remarkStr = inputText;
            };
        }
    }];
}

#pragma mark - contactsDelegate
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContacts:(NSArray<CNContact *> *)contacts {
    
    // 同时选中多个联系人
    self.extennalAttendeesArray = [NSMutableArray array];
    self.extennalNameArray = [NSMutableArray array];
    for (CNContact *contact in contacts) {
        
        [self printContactInfo:contact];
    }
    self.extennalAttendeesStr = [self.extennalAttendeesArray jsonStringEncoded];
    NSMutableString *nameStr = [NSMutableString string];
    for (NSInteger i = 0; i < self.extennalNameArray.count; i++) {
        [nameStr appendString:self.extennalNameArray[i]];
        if (i != self.extennalNameArray.count - 1) {
            [nameStr appendString:@","];
        }
    }
    [self.dataValueArray replaceObjectAtIndex:3 withObject:nameStr];
    [self.tableView reloadData];
    DLog(@"%@",self.extennalAttendeesStr);
}

- (void)printContactInfo:(CNContact *)contact {
    
    NSString *givenName = contact.givenName;
    NSString *familyName = contact.familyName;
    NSString *name = [givenName isNotBlank] ? givenName : familyName;
    NSLog(@"givenName=%@, familyName=%@", givenName, familyName);
    NSArray *phoneNumbers = contact.phoneNumbers;
    NSString *phoneNumStr = @"";
    NSString *emailStr = @"";
    NSMutableDictionary *contactDict = [NSMutableDictionary dictionary];
    for (CNLabeledValue <CNPhoneNumber*> *phone in phoneNumbers) {
        
        NSString *label = phone.label;
        CNPhoneNumber *phonNumber = (CNPhoneNumber *)phone.value;
        phoneNumStr = phonNumber.stringValue;
        NSLog(@"label=%@, value=%@", label, phonNumber.stringValue);
    }
    
    for (CNLabeledValue *email in contact.emailAddresses) {
        
        emailStr = email.value;
        DLog(@"email : %@",email);
    }
    [contactDict setValue:name forKey:@"name"];
    [contactDict setValue:phoneNumStr forKey:@"phone"];
    [contactDict setValue:emailStr forKey:@"email"];
    [self.extennalNameArray addObject:name];
    [self.extennalAttendeesArray addObject:contactDict];
}

#pragma mark - action
- (void)confirmBtnAction{
    
    for (NSInteger i = 0; i < self.dataValueArray.count; i++) {
        
        NSString *value = self.dataValueArray[i];
        if (![value isNotBlank]) {
            
            NSString *text = self.textFieldArray[i];
            [JRToast showWithText:[NSString stringWithFormat:@"%@ must be not null",[text substringToIndex:text.length - 1]] duration:2];
            return;
        }
    }
    
    if (![self.timeValueArray[0] isNotBlank]) {

        [JRToast showWithText:[NSString stringWithFormat:@"%@ must be not null",@"Start time"] duration:2];
        return;
    }
    if (![self.timeValueArray[1] isNotBlank]) {

        [JRToast showWithText:[NSString stringWithFormat:@"%@ must be not null",@"End time"] duration:2];
        return;
    }
    
    NSDate *startDate = [NSDate dateWithString:self.timeValueArray[0] format:@"yyyy-MM-dd HH:mm"];
    NSInteger startTimestamp = [startDate timeIntervalSince1970];
    NSDate *endDate = [NSDate dateWithString:self.timeValueArray[1] format:@"yyyy-MM-dd HH:mm"];
    NSInteger endTimeStamp = [endDate timeIntervalSince1970];
    if (endTimeStamp - startTimestamp < 30 * 60) {

        [JRToast showWithText:@"endTime must be greater than 30 min" duration:2];
        return;
    }
    if (endTimeStamp - startTimestamp > 4 * 60 * 60) {

        [JRToast showWithText:@"meeting must be in 4 Hour" duration:2];
        return;
    }
}

#pragma mark - CellDelegate
- (void)textFieldCellInput:(HYTextFieldTableViewCell *)cell inputStr:(NSString *)inputStr{
    
    if (cell.indexPath.row == 0) {
        
        [self.dataValueArray replaceObjectAtIndex:0 withObject:inputStr];

    }
}

#pragma mark - PGDatePickerDelegate
- (void)datePicker:(PGDatePicker *)datePicker didSelectDate:(NSDateComponents *)dateComponents{

    NSLog(@"%@",dateComponents);

    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *selectDate = [gregorianCalendar dateFromComponents:dateComponents];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *dateStr = [dateFormatter stringFromDate:selectDate];

    [self.timeValueArray replaceObjectAtIndex:self.lastSelectTimeIndex withObject:dateStr];
    [self.tableView reloadData];
}

#pragma mark - lazyload
- (HYTableViewDataSource *)dataSource{
    
    if (!_dataSource) {
        _dataSource = [HYTableViewDataSource new];
    }
    return _dataSource;
}

- (NSMutableArray *)dataSetsArray{
    
    if (!_dataSetsArray) {
        _dataSetsArray = [NSMutableArray array];
    }
    return _dataSetsArray;
}

- (NSMutableArray *)sectionArray{
    
    if (!_sectionArray) {
        _sectionArray = [NSMutableArray array];
    }
    return _sectionArray;
}

-(NSArray *)textFieldArray{
    if (!_textFieldArray) {
        _textFieldArray =  @[@"MeetingName:",@"Organizer:",@"Internal attendees:",@"extenal attendees"];;
    }
    return _textFieldArray;
}

-(NSMutableArray *)dataValueArray{
    if (!_dataValueArray) {
        _dataValueArray = [NSMutableArray arrayWithObjects:@"Staff Meeting",@"",@"",@"",nil];;
    }
    return _dataValueArray;
}

-(NSMutableArray *)timeValueArray{
    if (!_timeValueArray) {
        _timeValueArray = [NSMutableArray arrayWithObjects:@"",@"", nil];
    }
    return _timeValueArray;
}

- (HYTableViewDelegate *)delegate{
    
    if (!_delegate) {
        _delegate = [HYTableViewDelegate new];
    }
    return _delegate;
}

- (UITableView *)tableView{
    
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = KAPP_WHITE_COLOR;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self.delegate;
        _tableView.dataSource = self.dataSource;
        
    }
    return _tableView;
}

- (UIButton *)confirmBtn{
    
    if (!_confirmBtn) {
        
        _confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_confirmBtn setBackgroundColor:KAPP_THEME_COLOR];
        [_confirmBtn setTitle:@"OK" forState:UIControlStateNormal];
        [_confirmBtn setTitleColor:KAPP_WHITE_COLOR forState:UIControlStateNormal];
        _confirmBtn.titleLabel.font = KFitFont(16);
        [_confirmBtn addTarget:self action:@selector(confirmBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmBtn;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
